<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\model\XPotfpgoods;
use app\common\facade\Token;
use ba\Captcha;
use think\facade\Config;
use think\facade\Db;
use think\facade\Validate;
use app\common\controller\Backend;
use app\admin\model\AdminLog;

class Index extends Backend
{
    protected $noNeedLogin      = ['logout', 'login','index_sy'];
    protected $noNeedPermission = ['index'];
    protected $model=null;
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Codelib;
    }
    public function index()
    {
        $adminInfo          = $this->auth->getInfo();
        $adminInfo['super'] = $this->auth->isSuperAdmin();
        unset($adminInfo['token'], $adminInfo['refreshToken']);

        $menus = $this->auth->getMenus();
        if (!$menus) {
            $this->error(__('No background menu, please contact super administrator!'));
        }
        $this->success('', [
            'adminInfo'  => $adminInfo,
            'menus'      => $menus,
            'siteConfig' => [
                'site_name' => get_sys_config('site_name'),
                'version'   => get_sys_config('version'),
                'cdn_url'   => full_url(),
                'api_url'   => Config::get('buildadmin.api_url'),
                'upload'    => get_upload_config(),
            ],
            'terminal'   => [
                'install_service_port' => Config::get('terminal.install_service_port'),
                'npm_package_manager'  => Config::get('terminal.npm_package_manager'),
            ]
        ]);
    }

    public function login()
    {
        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'routePath' => '/admin'
            ], 302);
        }

        $captchaSwitch = Config::get('buildadmin.admin_login_captcha');

        // 检查提交
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keep     = $this->request->post('keep');

            $rule = [
                'username|' . __('Username') => 'require|length:3,30',
                'password|' . __('Password') => 'require|regex:^(?!.*[&<>"\'\n\r]).{6,32}$',
            ];
            $data = [
                'username' => $username,
                'password' => $password,
            ];
            if ($captchaSwitch) {
                $rule['captcha|' . __('Captcha')]     = 'require|length:4,6';
                $rule['captchaId|' . __('CaptchaId')] = 'require';

                $data['captcha']   = $this->request->post('captcha');
                $data['captchaId'] = $this->request->post('captcha_id');
            }
            $validate = Validate::rule($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            if ($captchaSwitch) {
                $captchaObj = new Captcha();
                if (!$captchaObj->check($data['captcha'], $data['captchaId'])) {
                    $this->error(__('Please enter the correct verification code'));
                }
            }

            AdminLog::setTitle(__('Login'));

            $res = $this->auth->login($username, $password, (bool)$keep);
            if ($res === true) {
                $this->success(__('Login succeeded!'), [
                    'userinfo'  => $this->auth->getInfo(),
                    'routePath' => '/admin'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: __('Incorrect user name or password!');
                $this->error($msg);
            }
        }

        $this->success('', [
            'captcha' => $captchaSwitch
        ]);
    }

    public function logout()
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refresh_token', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success();
        }
    }

    /**
     * 页面首页
     */
    public function index_sy(){

        $adminInfo          = $this->auth->getInfo();
        //图标层
        $code=$this->model->where('CODETYPE','alarmsetup')->order('REMIND','desc')->column('REMIND,code,codename');
        $data=[];
        $up=[];
        foreach ($code as $k=>$v) {
            $up[$k]['code']=$v['code'];
            $up[$k]['codename']=$v['codename'];
            if($v['code']=='DLXKZ'){
                $up[$k]['count']=Db::query("select  count(*) as count  from corplib where exists ( select * from X_CERTIFICATE where corp=corplib.corp and zjname='道路运营证' and datediff(day,getdate(),YXQDATE)<(select isnull(max(CAST(attr as int)),0) from codelib where code='DLXKZ' and codetype='alarmsetup') ) ")[0]['count'];
            }if($v['code']=='JSZ'){
                $up[$k]['count']=Db::query("select count(*) as count from x_driver,corplib where x_driver.CORP=corplib.CORP and datediff(day,getdate(),jszdate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='JSZ' and codetype='alarmsetup')   ")[0]['count'];
            }if($v['code']=='CLBX'){
                $up[$k]['count']=Db::query("select count(*) as count from x_carinfo,corplib where x_carinfo.corp=corplib.corp and datediff(day,getdate(),policydate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='CLBX' and codetype='alarmsetup')   ")[0]['count'];
            }if($v['code']=='CLNJ'){
                $up[$k]['count']=Db::query("select count(*) as count from x_carinfo,corplib where x_carinfo.corp=corplib.corp and datediff(day,getdate(),jydate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='CLNJ' and codetype='alarmsetup')  ")[0]['count'];
            }if($v['code']=='GXBX'){
                $up[$k]['count']=Db::query("select count(*) as count from x_insurance where valid='1' and datediff(day,getdate(),enddate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GXBX' and codetype='alarmsetup') ")[0]['count'];
            }if($v['code']=='GXNJ'){
                $up[$k]['count']=Db::query("select count(*) as count from (select tcno,MAX(nextcheckdate) as checkdate from X_POTCHECK group by tcno) a where datediff(day,getdate(),a.checkdate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GXNJ' and codetype='alarmsetup') ")[0]['count'];
            }if($v['code']=='AQZG'){
                $up[$k]['count']=Db::query("select count(*) as count from x_security,corplib where isnull(x_security.finished,'')<>'1' and corplib.companytype='供应商' and corplib.corp=x_security.corp  ")[0]['count'];
            }if($v['code']=='GYSHT'){
                $up[$k]['count']=Db::query("select count(*) as count  from corplib,x_contract where corplib.corp=x_contract.corp and corplib.companytype='供应商' and datediff(day,getdate(),x_contract.enddate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GYSHT' and codetype='alarmsetup' )  ")[0]['count'];
            }if($v['code']=='GYSZJ'){
                $up[$k]['count']=Db::query("select count(*) as count from x_certificate,corplib where corplib.COMPANYTYPE='供应商' and corplib.CORP=x_certificate.CORP and datediff(day,getdate(),yxqdate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GYSZJ' and codetype='alarmsetup')  ")[0]['count'];
            }if($v['code']=='KHHT'){
                $up[$k]['count']=Db::query("select count(*) as count  from corplib,x_contract where corplib.corp=x_contract.corp and corplib.companytype='客户' and datediff(day,getdate(),x_contract.enddate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GYSHT' and codetype='alarmsetup' ) and ( corplib.pflag='1' or  exists (select * from admin where corplib.DEPT=admin.department and admin.username='$adminInfo[username]') ) ")[0]['count'];
            }if($v['code']=='GXSQ'){
                $up[$k]['count']=Db::query("select count(*) as count from x_potsq where tkid not in ( select tkid from x_potfp) and op='$adminInfo[nickname]' ")[0]['count'];
            }if($v['code']=='GXFP'){
                $up[$k]['count']=Db::query("select count(*) as count from x_potsq where tkid not in ( select tkid from x_potfp) and tjflag='1' ")[0]['count'];
            }if($v['code']=='TSXX'){
                $up[$k]['count']=Db::query("select count(*) as count from complaintbody,complainthead,corplib where complaintbody.zgflag='0' and corplib.COMPANYTYPE='客户' and complainthead.billno=complaintbody.billno and complainthead.corpcode=corplib.corp  and (corplib.pflag='1' or exists (select * from admin where CHARINDEX(corplib.DEPT,admin.department)>0 and admin.username='$adminInfo[username]')) ")[0]['count'];
            }
        }
        $data['up']=$up;
        $data['thing']=Db::query("select top 10 * from X_PERSONALREMIND where op='$adminInfo[nickname]' and rq<=getdate() order by actived");
        $data['apply']=[
          '0'=>[
              'name'=>'配件采购',
              'approval_d'=>Db::query("select count(*) as count from x_stockbuy where dbo.f_getflowstatus(bizno)='待审批' and sqr='$adminInfo[nickname]'")[0]['count'],
              'approval_y'=>Db::query("select count(*) as count from x_stockbuy where dbo.f_getflowstatus(bizno)='已完成' and sqr='$adminInfo[nickname]'")[0]['count'],
              'approval_t'=>Db::query("select count(*) as count from x_stockbuy where dbo.f_getflowstatus(bizno)='已退回' and sqr='$adminInfo[nickname]'")[0]['count']
          ],
            '1'=>[
                'name'=>'供应商修改',
                'approval_d'=>Db::query("select count(*) as count from x_corpsq where dbo.f_getflowstatus(bizno)='待审批' and op='$adminInfo[nickname]'")[0]['count'],
                'approval_y'=>Db::query("select count(*) as count from x_corpsq where dbo.f_getflowstatus(bizno)='已完成' and op='$adminInfo[nickname]' ")[0]['count'],
                'approval_t'=>Db::query("select count(*) as count from x_corpsq where dbo.f_getflowstatus(bizno)='已退回' and op='$adminInfo[nickname]' ")[0]['count']
            ],
            '2'=>[
                'name'=>'罐箱维修审批',
                'approval_d'=>Db::query("select count(*) as count from x_repairrecord where dbo.f_getflowstatus(bizno)='待审批' and (op='$adminInfo[nickname]' or pf='$adminInfo[nickname]')")[0]['count'],
                'approval_y'=>Db::query("select count(*) as count from x_repairrecord where dbo.f_getflowstatus(bizno)='已完成' and (op='$adminInfo[nickname]' or pf='$adminInfo[nickname]')")[0]['count'],
                'approval_t'=>Db::query("select count(*) as count from x_repairrecord where dbo.f_getflowstatus(bizno)='已退回' and (op='$adminInfo[nickname]' or pf='$adminInfo[nickname]')")[0]['count']
            ],
            '3'=>[
                'name'=>'报价审核',
                'approval_d'=>Db::query("select count(*) as count from x_bjhead where dbo.f_getflowstatus(bjno)='待审批' and sales='$adminInfo[nickname]' and corptype='客户'")[0]['count'],
                'approval_y'=>Db::query("select count(*) as count from x_bjhead where dbo.f_getflowstatus(bjno)='已完成' and sales='$adminInfo[nickname]' and corptype='客户'")[0]['count'],
                'approval_t'=>Db::query("select count(*) as count from x_bjhead where dbo.f_getflowstatus(bjno)='已退回' and sales='$adminInfo[nickname]' and corptype='客户'")[0]['count']
            ],
        ];
        $data['flow']=[
            '0'=>[
                'name'=>'配件采购',
                'approval_d'=>Db::query("select count(*) as count from x_stockbuy,u_flowdata where x_stockbuy.bizno=u_flowdata.bizno and u_flowdata.username='$adminInfo[nickname]' and u_flowdata.iscurrent='1'")[0]['count'],
                'approval_y'=>Db::query("select count(*) as count from x_stockbuy,u_flowdata where x_stockbuy.bizno=u_flowdata.bizno and u_flowdata.username='$adminInfo[nickname]' and u_flowdata.statusflag='1'")[0]['count'],
            ],
            '1'=>[
                'name'=>'供应商修改',
                'approval_d'=>Db::query("select count(*) as count from x_corpsq,u_flowdata where x_corpsq.bizno=u_flowdata.bizno and u_flowdata.username='$adminInfo[nickname]' and u_flowdata.iscurrent='1'")[0]['count'],
                'approval_y'=>Db::query("select count(*) as count from x_corpsq,u_flowdata where x_corpsq.bizno=u_flowdata.bizno and u_flowdata.username='$adminInfo[nickname]' and u_flowdata.statusflag='1'")[0]['count'],
        ],
            '2'=>[
                'name'=>'罐箱维修审批',
                'approval_d'=>Db::query("select count(*) as count from x_repairrecord,u_flowdata where x_repairrecord.bizno=u_flowdata.bizno and u_flowdata.username='$adminInfo[nickname]' and u_flowdata.iscurrent='1'")[0]['count'],
                'approval_y'=>Db::query("select count(*) as count from x_repairrecord,u_flowdata where x_repairrecord.bizno=u_flowdata.bizno and u_flowdata.username='$adminInfo[nickname]' and u_flowdata.statusflag='1'")[0]['count'],
        ],
            '3'=>[
                'name'=>'报价审核',
                'approval_d'=>Db::query("select count(*) as count from x_bjhead,u_flowdata where x_bjhead.bjno=u_flowdata.bizno and u_flowdata.username='$adminInfo[nickname]' and u_flowdata.iscurrent='1' and x_bjhead.corptype='客户'")[0]['count'],
                'approval_y'=>Db::query("select count(*) as count from x_bjhead,u_flowdata where x_bjhead.bjno=u_flowdata.bizno and u_flowdata.username='$adminInfo[nickname]' and u_flowdata.statusflag='1' and x_bjhead.corptype='客户'")[0]['count'],
        ],
        ];
       $this->success('',$data);
    }

}
